package com.cda.pes.controller;

import com.cda.pes.VO.FavouriteVO;
import com.cda.pes.pojo.Favourite;
import com.cda.pes.pojo.Product;
import com.cda.pes.service.IFavouriteService;
import com.cda.pes.service.IProductService;
import com.cda.pes.service.ex.DeleteException;
import com.cda.pes.service.ex.InsertException;
import com.cda.pes.service.ex.ProductNotFoundException;
import com.cda.pes.util.JsonResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.List;

@RestController
@RequestMapping("favourites")
public class FavouriteController extends BaseController {
    @Autowired
    private IFavouriteService favouriteService;

//    @RequestMapping("insert")
//    public JsonResult<Favourite> insert(Favourite favourite){
//        Integer rows = favouriteService.findByPidAndUid(favourite.getPid(), favourite.getUid());
//        if (rows==1){
//            throw new InsertException("收藏商品时发生未知错误");
//        }
//        rows = favouriteService.insert(favourite);
//        if (rows!=1){
//            throw new InsertException("收藏商品时发生未知错误");
//        }
//        return new JsonResult<>(OK);
//    }
    @RequestMapping("insert")
    public JsonResult<Favourite> insert(Favourite favourite,HttpSession session){
        Integer uid = getuidFromSession(session);
        Integer pid = favourite.getPid();
        Integer rows = favouriteService.findByPidAndUid(uid,pid);
        if (rows==1){
            throw new InsertException("收藏商品时发生未知错误");
        }
        favourite.setUid(uid);
        favouriteService.insert(favourite);
        return new JsonResult<>(OK);
    }

    @RequestMapping({"","/"})
    public JsonResult<List<FavouriteVO>> findVOByUid(HttpSession session){
        List<FavouriteVO> data = favouriteService.findVOByUid(getuidFromSession(session));
        return new JsonResult<List<FavouriteVO>>(OK,data);
    }

    @RequestMapping("{fid}/delete")
    public JsonResult<Void> deleteFavourite(@PathVariable("fid") Integer fid){
        favouriteService.deleteFavourite(fid);
        return new JsonResult<>(OK);
    }
}
